package com.coincalf.config;

import com.alibaba.fastjson.JSON;
import com.coincalf.entity.User;
import com.coincalf.framework.enums.ResultCode;
import com.coincalf.framework.http.Response;
import com.coincalf.framework.utils.TokenUtil;
import com.coincalf.service.UserService;
import com.coincalf.web.CommonController;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * token拦截器
 */
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private static Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object apiResponse;
        try {
            log.info("当前请求接口={}", request.getRequestURI());
            // 验证有没有登录
            String token = request.getHeader("TOKEN");
            log.info("HTTP REQUEST URL ：{}  token={}", request.getRequestURL(), token);
            Map<String, Object> map = TokenUtil.parserToken(token);
            Object username;
            if (map != null && (username = map.get("username")) != null) {
                log.info("token校验 username={}", username);
                User user = userService.selectByPhone(username.toString());
                if (user == null) {
                    // 用户未找到（出现该情况可能是数据库被修改、app程序被修改，或tokenKey已泄露）
                    log.error(Strings.repeat("用户登录名=" + username + "未找到！若非人为修改，很可能「tokenKey」已被泄露！！！！！！！！！！！！！！！！！！！\n请立即更改！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！\n", 10));
                    apiResponse = Response.err(ResultCode.USER_NOT_EXIST);
                } else {
                    request.setAttribute(CommonController.LOGIN_SESSION, user);
                    request.setAttribute(CommonController.MOBILE, user.getMobile());
                    request.setAttribute(CommonController.USER_ID, user.getId());
                    return super.preHandle(request, response, handler);
                }
            } else {
                apiResponse = Response.err(ResultCode.TOKEN_VERIFY_FAIL);
            }
        } catch (Exception e) {
            log.error("token verify stop! {}", e.getMessage());
            apiResponse = Response.err(ResultCode.ERROR);
        }
        response.setContentType("application/json,charset=utf-8");
        response.getOutputStream().write(JSON.toJSON(apiResponse).toString().getBytes(StandardCharsets.UTF_8));
        return false;
    }

}
